package com.ruoyi.resumes.controller;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.servlet.http.HttpServletResponse;


import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.common.utils.poi.PdfUtil;
import com.ruoyi.common.utils.poi.WordUtil;

import com.ruoyi.resumes.mapper.ResumesMapper;
import freemarker.template.TemplateException;

import io.lettuce.core.output.SocketAddressOutput;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.resumes.domain.Resumes;
import com.ruoyi.resumes.service.IResumesService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;


/**
 * 简历管理Controller
 *
 * @author ruoyi
 * @date 2024-11-02
 */
/*@Anonymous*/
@RestController
@RequestMapping("/resumes/resumes")
public class ResumesController extends BaseController
{
    @Autowired
    private IResumesService resumesService;
    @Autowired
    private ResumesMapper resumesMapper;
    /**
     * 查询简历管理列表
     */
    @PreAuthorize("@ss.hasPermi('resumes:resumes:list')")
    @GetMapping("/list")
    public TableDataInfo list(Resumes resumes)
    {
        /*startPage();*/
        List<Resumes> list = resumesService.selectResumesList(resumes);
        return pagination(list);
    }

    /**
     * 导出简历管理列表
     */
    @PreAuthorize("@ss.hasPermi('resumes:resumes:export')")
    @Log(title = "简历管理", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, Resumes resumes)
    {
        List<Resumes> list = resumesService.selectResumesList(resumes);
        ExcelUtil<Resumes> util = new ExcelUtil<Resumes>(Resumes.class);
        util.exportExcel(response, list, "简历管理数据");
    }

    /**
     * 获取简历管理详细信息
     */
    @PreAuthorize("@ss.hasPermi('resumes:resumes:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(resumesService.selectResumesById(id));
    }

    /**
     * 新增简历管理
     */
    @PreAuthorize("@ss.hasPermi('resumes:resumes:add')")
    @Log(title = "简历管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody Resumes resumes)
    {
        return toAjax(resumesService.insertResumes(resumes));
    }

    /**
     * 修改简历管理
     */
    @PreAuthorize("@ss.hasPermi('resumes:resumes:edit')")
    @Log(title = "简历管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody Resumes resumes)
    {
        return toAjax(resumesService.updateResumes(resumes));
    }

    /**
     * 删除简历管理
     */
    @PreAuthorize("@ss.hasPermi('resumes:resumes:remove')")
    @Log(title = "简历管理", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(resumesService.deleteResumesByIds(ids));
    }

    /**
     * 简历导入
     */
    @Log(title = "简历管理", businessType = BusinessType.IMPORT)
    @PreAuthorize("@ss.hasPermi('resumes:resumes:import')")
    @PostMapping("/import")
    public AjaxResult importData(MultipartFile[] file) throws Exception {
        int num=file.length;
        int count=0;
        if(num==0){
            return error("请选择文件");
        }else{
            for(int i=0;i<num;i++){
                MultipartFile file1=file[i];
                //将pdf下载到本地
                String filepath=PdfUtil.save(file1);
                //获取pdf文档内容
                String content= PdfUtil.getContent(filepath);
                /*System.out.println(content);*/
                //封装简历信息
                Map<String,String> map=PdfUtil.setResume(content);
                Resumes resumes=new Resumes();
                resumes.setUserId(SecurityUtils.getUserId());
                resumes.setExperience(map.get("experience"));
                resumes.setEducation(map.get("education"));
                resumes.setSkills(map.get("skills"));
                resumes.setFileUrl(filepath);
/*                System.out.println("简历："+resumes.getExperience());*/
                int result=resumesService.insertResumes(resumes);
                if(result>0){
                    count++;
                }
                /*WordUtil wordUtil=new WordUtil();
                //获取将文件下载到指定目录下的路径 ruoyi/uploaddata/2024/11/30
                String path=wordUtil.save(file1);
                //获取word文档内容
                String content=wordUtil.getText(path);
                //获取简历信息
                Map<String,String> map=wordUtil.setResume(content);
                Resumes resumes=new Resumes();
                resumes.setUserId(SecurityUtils.getUserId());
                resumes.setExperience(map.get("experience"));
                resumes.setEducation(map.get("education"));
                resumes.setSkills(map.get("skills"));
                resumes.setFileUrl(path);
                resumesService.insertResumes(resumes);
                count++;*/
            }
        }
        if(count==1){
            return success("上传成功");
        }
        return error("上传失败");
    }
    /**
     * 简历模板下载
     * @return
     */
    /*
    @PostMapping("/importTemplate")
    public void importTemplate(HttpServletResponse response) throws IOException, TemplateException {
        //获取下载文件
        byte[] buf = resumesService.downloads();
        //文件名
        String fileName = "template.doc";
        //设置编码格式
        response.setCharacterEncoding("UTF-8");
        //解决下载下来的word不兼容
        response.setContentType("application/octet-stream");
        //设置文件长度
        response.setContentLength(buf.length);
        //设置文件名
        response.setHeader("Content-Disposition", "attachment;filename=".concat(fileName));
        //输出流
        response.getOutputStream().write(buf);
        //刷新缓存
        response.getOutputStream().flush();
        response.getOutputStream().close();
    }*/

    /**
     * 简历预览
     * @param id
     * @return
     * @throws IOException
     */
    @PreAuthorize("@ss.hasPermi('resumes:resumes:show')")
    @GetMapping("/show/{id}")
    public ResponseEntity<InputStreamResource> show(@PathVariable Long id) throws IOException {
        Resumes resumes=new Resumes();
        resumes=resumesService.selectResumesById(id);
        String path=resumes.getFileUrl();
        FileSystemResource file = new FileSystemResource(path);

        // 设置响应头
        HttpHeaders headers = new HttpHeaders();
        headers.add("Content-Disposition", String.format("attachment; filename=\"%s\"", file.getFilename()));

        return ResponseEntity
                .ok()
                .headers(headers)
                .contentLength(file.contentLength())
                .contentType(MediaType.parseMediaType("application/octet-stream"))
                .body(new InputStreamResource(file.getInputStream()));
    }

    @GetMapping("/isAdmin")
    public AjaxResult isAdmin(){
        Map<String,String> map=new HashMap<>();
        //获取当前用户id
        Long userId=SecurityUtils.getUserId();
        //获取role_id
        List roleId=resumesMapper.getRoleId(userId);
        if (roleId.contains(100)){
            map.put("role","应聘者");
        }else if(roleId.contains(1)){
            map.put("role","管理员");
        }else if(roleId.contains(103)){
            map.put("role","面试官");
        } else if(roleId.contains(101)){
            map.put("role","公司");
        }return success(map);
    }
}
